
const utility = require("utility")//密码加密

module.exports = class menusController extends require('egg').Controller {

    async login() {
        const { ctx } = this;
        const { username, password } = ctx.request.body
        const users = await ctx.adminModel.User.findLogin(username, password);
        if (users) {
            const tokenString = users.userId.toString()
            const token = utility.md5(tokenString + this.config.keys)
            await users.updateToken(token)
            await users.logSignin()

            ctx.status = 200
            ctx.msg = "获取成功"
            ctx.data = { token };
        } else {
            ctx.status = 401
            ctx.msg = "账号或者密码错误"
            ctx.data = '';
        }

    }

    async user() {
        const { ctx } = this;
        if (ctx.query.token) {
            const users = await ctx.adminModel.User.findByToken(ctx.query.token);
            ctx.status = 200
            ctx.msg = "获取成功"
            ctx.data = users
        } else {
            ctx.status = 200
            ctx.msg = "缺少token"
            ctx.data = ''
        }


    }

    async userList() {
        const { ctx } = this;

        const users = await ctx.adminModel.User.findAll();
        ctx.status = 200
        ctx.msg = "获取成功"
        ctx.data = users

    }

    async createbanner() {
        const validate = {
            keys: 'string',
            name: 'string',
            id: 'string?',
            pid: 'string?',
        }
        const { ctx } = this;
        ctx.validate(validate, ctx.request.body)
        if (ctx.request.body.id) {
            const id = parseInt(ctx.request.body.id)
            const example = await ctx.adminModel.Banner.findByPk(id);
            const result = await example.update(ctx.request.body);
            ctx.status = 200
            ctx.msg = "修改成功"
            ctx.data = result
        } else {
            const result = await ctx.adminModel.Banner.create(ctx.request.body);
            ctx.status = 200
            ctx.msg = "获取成功"
            ctx.data = result
        }

    }

    async banner() {
        const { ctx } = this;

        let { page = 1, count = 10, pid = 0 } = ctx.query;

        const result = await ctx.adminModel.Banner.findAndCountAll({
            limit: parseInt(count),
            offset: (page - 1) * count,
            where: {
                pid: pid,
            }
        }).then(res => {
            let result = {};
            result.data = res.rows;
            result.totalCount = res.count;
            return result;
        });
        ctx.status = 200
        ctx.msg = "获取成功"
        ctx.data = result
    }
    async destroy(){
        const { ctx } = this;
        let { id} = ctx.query;
        const example = await ctx.adminModel.Banner.findByPk(id);
        const result = await example.destroy({truncate: true, force: true});
        ctx.status = 200
        ctx.msg = "获取成功"
        ctx.data = result

    }
}
